/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package My139;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import my12306.bean.QueryResult;
import my12306.http.Consts;
import my12306.http.HttpClientUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Jack
 */
public class My139Client {

    private final static org.slf4j.Logger log = LoggerFactory.getLogger(SMSFrame.class);
    private static final HttpClient httpClient = HttpClientUtils.getHttpsClient();
    private static My139Client instance;
    Random random = new Random(System.currentTimeMillis());

    private My139Client() {
    }

    public String getCookieValue(HttpClient httpClient, String key) {
        List<Cookie> cookies = ((DefaultHttpClient) httpClient).getCookieStore().getCookies();
        String result = "";
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                result = cookie.getValue();
                break;
            }
        }
        return result;
    }

    public String getSid() {
        try {
            String sid = getCookieValue(httpClient, "UserData");
            sid = java.net.URLDecoder.decode(sid, "UTF-8");
            JSONObject json = new JSONObject(sid);
            sid = json.getString("ssoSid");
            return sid;
        } catch (UnsupportedEncodingException ex) {
            log.error(ex.getLocalizedMessage(), ex);
        } catch (JSONException ex) {
            log.error(ex.getLocalizedMessage(), ex);
        }
        return null;
    }

    /**
     * 1. login
     */
    public QueryResult login(String uid, String pwd) {
        QueryResult rs = new QueryResult();
        HttpPost post = null;
        String response = null;
        try {
            post = new HttpPost("https://mail.10086.cn/Login/Login.ashx?_fv=5");
            post.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:20.0) Gecko/20130106 Firefox/20.0");
            post.addHeader(Consts.Accept_Header, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader(Consts.Connection_Header, Consts.Connection);
            post.addHeader(Consts.Host_Header, "mail.10086.cn");
            post.addHeader(Consts.Referer_Header, "http://mail.10086.cn/default.html");
            post.addHeader("Content-Type", "application/x-www-form-urlencoded");

            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("Password", pwd));
            parameters.add(new BasicNameValuePair("UserName", uid));
            parameters.add(new BasicNameValuePair("VerifyCode", ""));

            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
            post.setEntity(uef);

            response = httpClient.execute(post, new BasicResponseHandler());
            log.info(response);
            rs.setMsg(response);
            rs.setRawData(response);
            rs.setState(QueryResult.SUCC);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            post.releaseConnection();
        }
        return rs;

    }

    /**
     * 2. BehaviorGather
     */
    public QueryResult behaviorGather() {
        QueryResult rs = new QueryResult();
        HttpPost post = null;
        String response = null;
        try {
            String url = "http://g2.mail.10086.cn/Behavior/BehaviorGather.ashx?sid=%s&rnd=%s";
            url = String.format(url, getSid(), "" + random.nextDouble());
            post = new HttpPost(url);
            post.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:20.0) Gecko/20130106 Firefox/20.0");
            post.addHeader(Consts.Accept_Header, "*/*");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader(Consts.Connection_Header, Consts.Connection);
            post.addHeader(Consts.Host_Header, "g2.mail.10086.cn");
            post.addHeader(Consts.Referer_Header, "http://g2.mail.10086.cn/welcome.html?Sid=" + getSid());
            post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            post.addHeader("X-Requested-With", "XMLHttpRequest");

            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("reports", "<reports><behavior id='10102' extendID='0' mid='35' index='19' pageId='122010510011' actionType='20' ext1='' ext2=''/></reports>"));


            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
            post.setEntity(uef);

            response = httpClient.execute(post, new BasicResponseHandler());

            log.info(response);


            rs.setMsg(response);
            rs.setRawData(response);
            rs.setState(QueryResult.SUCC);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            post.releaseConnection();
        }
        return rs;

    }

    /**
     * 3. getAllFolders
     */
    public QueryResult getAllFolders() {
        QueryResult rs = new QueryResult();
        HttpPost post = null;
        String response = null;
        try {
            String url = "http://appmail.mail.10086.cn/s?func=mbox:getAllFolders&sid=%s&RMKEY=&randnum=%s";
            url = String.format(url, getSid(), "" + random.nextDouble());
            post = new HttpPost(url);
            post.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:20.0) Gecko/20130106 Firefox/20.0");
            post.addHeader(Consts.Accept_Header, "text/javascript");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader(Consts.Connection_Header, Consts.Connection);
            post.addHeader(Consts.Host_Header, "appmail.mail.10086.cn");
            String ref = "http://appmail.mail.10086.cn/main.htm?func=global:execTemp&sid=%s&rnd=134";
            ref = String.format(ref, getSid());
            post.addHeader(Consts.Referer_Header, ref);
            post.addHeader("Content-Type", "application/xml; charset=UTF-8");
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("reports", "<reports><behavior id='10102' extendID='0' mid='35' index='19' pageId='122010510011' actionType='20' ext1='' ext2=''/></reports>"));


            StringEntity xlmData = new StringEntity("<object> <int name=\"stats\">1</int> <int name=\"type\">0</int> </object>");
            post.setEntity(xlmData);

            response = httpClient.execute(post, new BasicResponseHandler());

            log.info(response);
            rs.setMsg(response);
            rs.setRawData(response);
            rs.setState(QueryResult.SUCC);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            post.releaseConnection();
        }
        return rs;

    }

    /**
     * 4. sendSms
     */
    public QueryResult sendSms(String msg, String mob) {
        QueryResult rs = new QueryResult();
        HttpPost post = null;
        String response = null;
        try {
            String url = "http://smsrebuild1.mail.10086.cn/sms/sms?func=sms:sendSms&sid=%s&rnd=%s";
            url = String.format(url, getSid(), "" + random.nextDouble());
            post = new HttpPost(url);
            post.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:20.0) Gecko/20130106 Firefox/20.0");
            post.addHeader(Consts.Accept_Header, "*/*");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader(Consts.Connection_Header, Consts.Connection);
            post.addHeader(Consts.Host_Header, "smsrebuild1.mail.10086.cn");
            String ref = "http://smsrebuild1.mail.10086.cn/sms/smsmms/superman/send.htm?sid=%s&rnd=%s";
            ref = String.format(ref, getSid(), "" + random.nextDouble());
            post.addHeader(Consts.Referer_Header, ref);
            post.addHeader("Content-Type", "application/xml;charset=utf-8");
            post.addHeader("X-Requested-With", "XMLHttpRequest");

//            String SMS = "你好，该吃饭了。" + System.currentTimeMillis();
//            String mob = "8613660351283";
            String msgData = "<object><int name=\"doubleMsg\">0</int><int name=\"submitType\">1</int><string name=\"smsContent\">%s</string><string name=\"receiverNumber\">%s</string><string name=\"comeFrom\">104</string><int name=\"sendType\">0</int><int name=\"smsType\">1</int><int name=\"serialId\">-1</int><int name=\"isShareSms\">0</int><string name=\"sendTime\"></string><string name=\"validImg\"></string><int name=\"groupLength\">50</int></object>";
            msgData = String.format(msgData, msg, mob);
            StringEntity xlmData = new StringEntity(msgData, "UTF-8");

            post.setEntity(xlmData);

            response = httpClient.execute(post, new BasicResponseHandler());

            log.info(response);

            rs.setMsg(response);
            rs.setRawData(response);
            rs.setState(QueryResult.SUCC);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            post.releaseConnection();
        }
        return rs;

    }

    /**
     * 5. AutosaveContact
     */
    public QueryResult autosaveContact(String msg, String mob) {
        QueryResult rs = new QueryResult();
        HttpPost post = null;
        String response = null;
        try {
            String url = "http://g2.mail.10086.cn/addr/apiserver/AutosaveContact.ashx?sid=%s&rnd=%s";
            url = String.format(url, getSid(), "" + random.nextDouble());
            post = new HttpPost(url);
            post.addHeader(HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:20.0) Gecko/20130106 Firefox/20.0");
            post.addHeader(Consts.Accept_Header, "*/*");
            post.addHeader("Cache-Control", "no-cache");
            post.addHeader(Consts.Connection_Header, Consts.Connection);
            post.addHeader(Consts.Host_Header, "g2.mail.10086.cn");
            String ref = "http://g2.mail.10086.cn/welcome.html?Sid=" + getSid();
            post.addHeader(Consts.Referer_Header, ref);
            post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            post.addHeader("X-Requested-With", "XMLHttpRequest");

            ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
            String data = "<AddLastContacts><AddContactsInfo><SerialId>590934853</SerialId><AddrName>%2$s</AddrName><AddrType>M</AddrType><AddrContent>%2$s</AddrContent><AddrMobile>%2$s</AddrMobile><AddrId>0</AddrId><AddrTitle>%1$s</AddrTitle><ComeFrom>1</ComeFrom></AddContactsInfo></AddLastContacts>";
            data = String.format(data, msg, mob);
            parameters.add(new BasicNameValuePair("xml", data));

            UrlEncodedFormEntity uef = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
            post.setEntity(uef);

            response = httpClient.execute(post, new BasicResponseHandler());

            log.info(response);

            rs.setMsg(response);
            rs.setRawData(response);
            rs.setState(QueryResult.SUCC);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            post.releaseConnection();
        }
        return rs;

    }

    /**
     * @return the httpClient
     */
    public static HttpClient getHttpClient() {
        return httpClient;
    }

    /**
     * @return the instance
     */
    public static My139Client getInstance() {
        if (instance == null) {
            instance = new My139Client();
        }
        return instance;
    }
}
